import _ from "lodash";
import { Component, Vue, Prop } from "vue-property-decorator";
import { desktopCapturer, DesktopCapturerSource, screen as electronScreen, ipcRenderer, SourcesOptions } from 'electron';
import { REGISTER_KEY } from '@/bglib/shortcut';

/** 按键截图频道 */
const KEY_FOR_SHOT = "key_for_shot";

@Component
export default class Screenshot extends Vue {

    public is_get_screenshot = false;

    async created() {

        ipcRenderer.on(KEY_FOR_SHOT, () => {
            this.shot();
        })
        // 注册截图键
        await this.$ipcR.send(REGISTER_KEY, { key: "Ctrl+Alt+O", channel: KEY_FOR_SHOT });

    }

    async shot() {
        this.is_get_screenshot = true;

        const thumbSize = this.determineScreenShotSize()

        let p = (option: SourcesOptions) => new Promise<DesktopCapturerSource[]>(
            (resolve, reject) => desktopCapturer.getSources(
                option,
                (error: Error, sources: DesktopCapturerSource[]) => {
                    if (error) { reject(error); }
                    else { resolve(sources); }
                }
            )
        );

        try {
            let [desk] = await p({ types: ["screen"], thumbnailSize: thumbSize });
            console.log(desk);
            const myimg = this.$refs.my_img as HTMLMediaElement
            myimg.src = desk.thumbnail.toDataURL();
        } catch (error) {
            console.log(error)
        }

        this.is_get_screenshot = false;
    }


    determineScreenShotSize() {
        const screenSize = electronScreen.getPrimaryDisplay().workAreaSize
        const maxDimension = Math.max(screenSize.width, screenSize.height)
        return {
            width: maxDimension * window.devicePixelRatio,
            height: maxDimension * window.devicePixelRatio
        }
    }

    async screenVideo() {
        desktopCapturer.getSources(
            { types: [/*"window",*/ "screen"] },
            (error: Error, sources: DesktopCapturerSource[]) => {
                let desk = sources[0];

                let option = { audio: false, video: {} };
                _.set(option, "video.mandatory", {
                    chromeMediaSource: 'desktop',
                    chromeMediaSourceId: desk.id,
                    minWidth: 1920,
                    maxWidth: 1920,
                    minHeight: 1080,
                    maxHeight: 1080
                });
                //console.log(this.$refs.my_video);


                navigator.mediaDevices
                    .getUserMedia(option)
                    .then((stream) => {
                        const video = this.$refs.my_video as HTMLMediaElement
                        video.srcObject = stream
                        video.onloadedmetadata = (e) => {
                            video.play();
                        }
                    })
                    .catch((e) => console.log(e));

            }
        );

    }

}